<?php 
// http://localhost/vnsupplier/admin/createAdminListPage.php?t=users
include "../Lib/Common.php";
if (!isset($act)) {
	//---------= Start read schemal ----------------------------------------------------------------------------------------------
	// database constants
	// make sure the information is correct
	define("DB_SERVER", DATABASE_HOST);
	define("DB_USER", DATABASE_USER);
	define("DB_PASS", DATABASE_PASSWORD);
	define("DB_NAME", DATABASE_NAME);

	// connection to the database
	$dbhandle = mysql_connect(DB_SERVER, DB_USER, DB_PASS)
	   or die("Unable to connect to MySQL");

	// select a database to work with
	$selected = mysql_select_db(DB_NAME, $dbhandle)
	   or die("Could not select examples");

	// return all available tables 
	$result_tbl = mysql_query( "SHOW TABLES FROM ".DB_NAME, $dbhandle );

	$tables = array();
	while ($row = mysql_fetch_row($result_tbl)) {
	   $tables[] = $row[0];
	}
	$cols = 0;
	$tableName = $t;
	//print_r($tables);
	foreach ( $tables as $table ) {
	   $result_fld = mysql_query( "SHOW FIELDS FROM ".$table, $dbhandle );
	   if ($table == $t) {
		   while( $row1 = mysql_fetch_row($result_fld) ) {
			  if ($row1[3] != "PRI") { // PrimaryKey
				$cols++;
				if (!isset($defaultSortField)) $defaultSortField = $row1[0];
				${"FieldName$cols"} = $row1[0];
				${"HasSort$cols"}	= "true";
				${"SortTips$cols"}	= "Sort by ".$row1[0];
				${"Width$cols"}		= "";
				${"Align$cols"}		= "";
				${"ColumnTitle$cols"}	= $row1[0];
				${"GetFrom$cols"}	= "";
			  } else $primaryKeyName = $row1[0];
		   }
	   }
	}
}
mysql_close($dbhandle);
// init start values for creating admin page (List page)
if (!isset($pageName)) $pageName = "list.php";
if (!isset($titlePage)) $titlePage= "Demo Listing";
if (!isset($updatePage)) $updatePage	= "detail.php";
if (!isset($formName)) $formName = "frmMain";
if (!isset($tableName)) $tableName= "allfields";
if (!isset($primaryKeyName)) $primaryKeyName = "ID";
if (!isset($defaultSortField)) $defaultSortField = "FVarchar";

if (!isset($cols)) $cols = 1;
if (isset($act) && $act=="CREATE") {
	//$columns[] = array("FieldName"=>"FVarchar", "HasSort"=>true /* Sort */, "SortTips"=>"Sort by FVarchar", "Width"=>"50%" /* Width */, "Align"=>"Left" /* Align */, "ColumnTitle"=>"FVarchar");
	//$columns[] = array("FieldName"=>"FNumeric", "HasSort"=>true /* Sort */, "SortTips"=>"Sort by FNumeric", "Width"=>"10%" /* Width */, "Align"=>"Right" /* Align */, "ColumnTitle"=>"FNumeric");
	//$columns[] = array("FieldName"=>"FDate", "HasSort"=>true /* Sort */, "SortTips"=>"Sort by FDate", "Width"=>"20%" /* Width */, "Align"=>"Center" /* Align */, "ColumnTitle"=>"FDate");
	for ($i=1; $i<=$cols;$i++) {
		$columns[] = array("FieldName"=>${"FieldName$i"}, "HasSort"=>${"HasSort$i"} /* Sort */, "SortTips"=>${"SortTips$i"}, 
						"Width"=>${"Width$i"} /* Width */, "Align"=>${"Align$i"} /* Align */, "ColumnTitle"=>${"ColumnTitle$i"}, "GetFrom"=>${"GetFrom$i"});
	}
	// Create list page base on init values
	$listColumns = "";
	$listColumnData = "";
	$joinRowCount = "";
	$joinGetList = "";
	$joinTables = array();
	$onFields = array();
	$getFields = array();
	for ($i=0; $i<count($columns); $i++) {
		$column = $columns[$i];
		if (trim($column["FieldName"])!="") {
			$listColumns = $listColumns."\n";
			$listColumns = $listColumns."<td width=\"".$column["Width"]."\" nowrap>";
			if ($column["HasSort"]) {
				$sortName = $column["FieldName"];
				if ($column["GetFrom"]!="")
				{
					$args = explode(",", $column["GetFrom"]);
					$sortName = $args[0].".".$args[1];
				}
				$listColumns = $listColumns. "<a href=\"#\" onClick=\"_sort('$sortName', document.<?php  echo \$frmName;?>);\"";
				$listColumns = $listColumns. " class=\"adminGridHeaderLink\" title=\"".$column["SortTips"]."\"><b>".$column["ColumnTitle"]."</b></a>";
			}
			else
				$listColumns = $listColumns. "<b>".$column["ColumnTitle"]."</b>";
			$listColumns = $listColumns. "</td>";
			if ($column["GetFrom"]!="")
			{
				$args = explode(",", $column["GetFrom"]);
				$joinTables[] = $args[0];
				$onFields[] = $tableName.".".$column["FieldName"]."=".$args[0].".id";
				$getFields[] = $args[1];
				$listColumnData = $listColumnData."<td align=\"".$column["Align"]."\"><?php  echo \$".$tableName."->otherFields['".$args[0]."_".$args[1]."'];?></td>";
			} else
				$listColumnData = $listColumnData. "<td align=\"".$column["Align"]."\"><?php  echo \$".$tableName."->".$column["FieldName"].";?></td>";
		}
	}
	$joinRowCount = ", array(";
	$joinGetList = ", array(";						 
	for ($i=0; $i<count($joinTables); $i++)
	{
		$joinRowCount .= ($i==0?"":",")."'".$joinTables[$i]."'";
		$joinGetList .= ($i==0?"":",")."'".$joinTables[$i]."'";
	}
	$joinRowCount .= "), array(";
	$joinGetList .= "), array(";
	for ($i=0; $i<count($onFields); $i++)
	{
		$joinRowCount .= ($i==0?"":",")."'".$onFields[$i]."'";
		$joinGetList .= ($i==0?"":",")."'".$onFields[$i]."'";
	}
	$joinRowCount .= ")";
	$joinGetList .= "), array(";
	for ($i=0; $i<count($getFields); $i++)
	{
		$joinGetList .= ($i==0?"":",")."'".$getFields[$i]."'";
	}
	$joinGetList .= ")";
	
	// get contents of listTemplate.php
	$filename = "./listTemplate.tmpl";
	
	$handle = fopen($filename, "r");
	$contents = fread($handle, filesize($filename));
	fclose($handle);

	// Replace variables in contents
	$contents = str_replace("{pageName}", $pageName, $contents);
	$contents = str_replace("{titlePage}", $titlePage, $contents);
	$contents = str_replace("{updatePage}", $updatePage, $contents);
	$contents = str_replace("{formName}", $formName, $contents);
	$contents = str_replace("{tableName}", $tableName, $contents);
	$contents = str_replace("{primaryKeyName}", $primaryKeyName, $contents);
	$contents = str_replace("{defaultSortField}", $defaultSortField, $contents);
	$contents = str_replace("{listColumns}", $listColumns, $contents);
	$contents = str_replace("{listColumnData}", $listColumnData, $contents);
	$contents = str_replace("{joinRowCount}", $joinRowCount, $contents);
	$contents = str_replace("{joinGetList}", $joinGetList, $contents);

	$createdPage = $pageName;
	if (isset($createdDir) && $createdDir!="")
	{
		$dir = CreateDir($createdDir);
		$createdPage = $dir."/".$pageName;
	}
	$handle = fopen($createdPage, "w");

	fwrite($handle, $contents);

	fclose($handle);

	echo "Page Listing has created.";
}
?>
<script>
function AddColumn(col) {
	document.frmMain.cols.value = col;
	document.frmMain.submit();
}
function Create() {
	document.frmMain.act.value = "CREATE";
	document.frmMain.submit();
}
</script>
<form name=frmMain method=post>
<input type=hidden name=cols value="<?php  echo $cols;?>">
<input type=hidden name=act>
<b>CREATE PAGE LISTING</b> <br>
<table>
	<tr>
		<td width="150">Page PHP name:</td>
		<td> <input type=text name=pageName value="<?php  echo $pageName;?>"></td>
	</tr>
	<tr>
		<td>Page title:</td>
		<td><input type=text name=titlePage value="<?php  echo $titlePage;?>"></td>
	</tr>
	<tr>
		<td>Page PHP for updating:</td>
		<td><input type=text name=updatePage value="<?php  echo $updatePage;?>"></td>
	</tr>
	<tr>
		<td>Form name:</td>
		<td><input type=text name=formName value="<?php  echo $formName;?>"></td>
	</tr>
	<tr>
		<td>Table name:</td>
		<td><input type=text name=tableName value="<?php  echo $tableName;?>"></td>
	</tr>
	<tr>
		<td>Primary key name: </td>
		<td><input type=text name=primaryKeyName value="<?php  echo $primaryKeyName;?>"></td>
	</tr>
	<tr>
		<td>Default sort field: </td>
		<td><input type=text name=defaultSortField value="<?php  echo $defaultSortField;?>"></td>
	</tr>
	<tr>
		<td>Created directory: </td>
		<td><input type=text name=createdDir value="<?php  echo $createdDir;?>"></td>
	</tr>
	<tr>
		<td></td>
		<td></td>
	</tr>
</table>
<?php  for ($i=1; $i<=$cols; $i++) {?>
<b>Field <?php  echo $i;?>:</b><br>
&nbsp; &nbsp; Field name: <input type=text name="FieldName<?php  echo $i;?>" value="<?php  if (isset(${"FieldName$i"})) echo ${"FieldName$i"};?>" style="width:100px"> &nbsp; 
	Sort: <input type=text name=HasSort<?php  echo $i;?> value="<?php  if (isset(${"HasSort$i"})) echo ${"HasSort$i"};?>" style="width:40px"> &nbsp; 
	Tips: <input type=text name=SortTips<?php  echo $i;?> value="<?php  if (isset(${"SortTips$i"})) echo ${"SortTips$i"};?>"> &nbsp; 
	Width: <input type=text name=Width<?php  echo $i;?> value="<?php  if (isset(${"Width$i"})) echo ${"Width$i"};?>" style="width:50px"> &nbsp; 
	Align: <input type=text name=Align<?php  echo $i;?> value="<?php  if (isset(${"Align$i"})) echo ${"Align$i"};?>" style="width:50px"> &nbsp; 
	Title: <input type=text name=ColumnTitle<?php  echo $i;?> value="<?php  if (isset(${"ColumnTitle$i"})) echo ${"ColumnTitle$i"};?>"> &nbsp; 
	Get from: <input type=text name=GetFrom<?php  echo $i;?> value="<?php  if (isset(${"GetFrom$i"})) echo ${"GetFrom$i"};?>"> tablebName,displayField &nbsp; <br>
<?php  }?>
<br>
<input type=button value="Add Column" onClick="AddColumn(<?php  echo ($cols+1);?>);"> &nbsp; 
<input type=button value="Create page" onClick="Create();"> &nbsp; 
</form>